package com.qiqu;


import com.qiqu.utils.JSONResult;
import com.qiqu.utils.JsonUtils;
import com.qiqu.utils.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class MiniInterceptor implements HandlerInterceptor {

    @Autowired
    RedisOperator redis;

    public static final String USER_REDIS_SESSION ="user_redis_session";

     /*
     * 拦截请求，在controller调用前
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //返回false表示请求拦截，true表示请求通过
        String userId=request.getHeader("userId");
        String userToken=request.getHeader("userToken");
        if(StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(userToken)){
             String token = redis.get(USER_REDIS_SESSION+":"+userId);
             if(StringUtils.isEmpty(token) && StringUtils.isBlank(token)){
                   //token为空或者已经过期
                  returnErrorResponse(response, JSONResult.errorTokenMsg("请登录...."));
                  return false;
             }else {
                 if(!token.equals(userToken)){
                     //判断是否在同一设备登录
                     returnErrorResponse(response,JSONResult.errorTokenMsg("账户异常..."));
                     return false;
                 }
             }
        }else {
            returnErrorResponse(response,JSONResult.errorTokenMsg("请登录..."));
            return false;
        }
        return true;
    }
    //以json的形式把拦截错处信息返回给前端
    public void returnErrorResponse(HttpServletResponse response, JSONResult result) throws IOException {
        OutputStream out =null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out =response.getOutputStream();
            out.write(JsonUtils.objectToJson(result).getBytes(StandardCharsets.UTF_8));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(out !=null){
                out.close();
            }
        }
    }


    /*
     * 调用controller之后，渲染视图之前
     * */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    /*
     * 请求controller,渲染视图后
     * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }


}
